<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { sendServiceData } from '../../common/service'
import { loginSystemApi, queryCodeImgApi, updateUserPasswordApi } from '../../common/service/api/userApi'
import { useRouter } from 'vue-router'
import { resetDefaultRoute } from '../../router'
import { appState, initUserLoginInfo } from '../../common/manager/appManager'
import { Base64 } from 'js-base64'
import { popMessage } from '../../common/utils/normalUtils'
import Loading from '../../components/normal/Loading.vue'
import { useDiyFormValid } from '../../common/hooks/FormValidHooks'


const state:any = reactive({
  sysName: appState.name,
  sysNameType: appState.platform,
  remCatch: false,
  changePassword: false,
  send: {
    username: '',
    password: '',
    code: '',
    uuid: ''
  },
  // temp?-----------------------------
  error: {
    username: '',
    password: '',
    code: ''
  },
  imgLoading: false,
  isLoading: false,
  imageSource: '',
  rules: {
    username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
    password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
  },

  // ------------------------------------------------------------------- 放一个视图 不加了
  send2: {
    oldPassword: '',
    newPassword: '',
    reNewPassword: ''
  },
  error2: {
    oldPassword: '',
    newPassword: '',
    reNewPassword: ''
  },
  rules2: {
    newPassword: [{ required: true, message: '新密码不能为空', trigger: 'blur' }],
    reNewPassword: [{ required: true, message: '重复密码不能为空', trigger: 'blur' },
      {
        validator: () => {
          return state.send2.newPassword === state.send2.reNewPassword
        },
        message: '两次输入密码不同',
        trigger: 'blur'
      }]
  }
})

const router = useRouter()

// 简单扩展下
const { actions } = useDiyFormValid()
actions.getFormOptions = () => {
  if (state.changePassword) {
    return {
      formData: state.send2,
      error: state.error2,
      rules: state.rules2
    }
  }
  return { formData: state.send, error: state.error, rules: state.rules }
}

/**
 * 登录处理
 */
const loginHandler = async () => {
  // 验证表达
  if (!actions.validForm()) return
  if (!state.send.uuid) {
    popMessage('验证码验证失败！')
    return
  }
  // 登录请求
  const send = { ...state.send }
  const result = await sendServiceData(loginSystemApi, send, state, true, true)
  if (!result) {
    queryCodeImg()
    return
  }

  // 初始化用户信息
  await initUserLoginInfo({
    userName: send.username,
    userId: result.userId,
    token: result.token
  })
  // 记住登录信息
  if (state.remCatch) catchUserPwd()
  else clearUserPwd()

  // 其他提示信息
  if (result.promptMessage) {
    popMessage(result.promptMessage)
  }

  // 首次登录，需修改密码
  if (String(result.loginFlag) === '0') {
    state.changePassword = true
    state.send2.oldPassword = send.password
    return
  }
  // 调整默认或缓存页面
  resetDefaultRoute()
}


/**
 * 记住登录信息
 */
const catchUserPwd = () => {
    // 简单base64存下 不加密了
    let { username, password } = state.send
    if (state.changePassword)password = state.send2.newPassword
    const name = Base64.toBase64(username)
    const info = String(name.length + 'AF' + name) + Base64.toBase64(password)
    localStorage.setItem('_c_uu_f', Base64.toBase64(info))
}

/**
 * 清除
 */
const clearUserPwd = () => {
    localStorage.removeItem('_c_uu_f')
}

/**
 * 初始化登录信息
 */
const initUserPwd = () => {
  let info = localStorage.getItem('_c_uu_f')
  if (!info) return
  info = Base64.fromBase64(info)
  const index = info.indexOf('AF')
  if (index < 1) return
  const len = parseInt(info.substring(0, index), 10)
  if (isNaN(len)) return
  info = info.substring(index + 2, info.length)
  const username = Base64.fromBase64(info.substring(0, len))
  const password = Base64.fromBase64(info.substring(len, info.length))
  Object.assign(state.send, {
    username,
    password
  })
  state.remCatch = true
}


/**
 * 查询验证码
 */
const queryCodeImg = async () => {
    const result = await sendServiceData(queryCodeImgApi, {}, state)
    if (!result || !result.img) {
      popMessage('验证码获取失败请刷新页面重新尝试！')
      state.send.uuid = ''
      state.imageSource = ''
      return
    }
    state.send.uuid = result.uuid
    state.imageSource = 'data:image/gif;base64,' + result.img
}

// 初始化
onMounted(() => {
    // 读取缓存
    initUserPwd()
    // 查询验证码
    queryCodeImg()
})

// --------------------------------------------------- change password -----------------------------------------------------
/**
 *
 */
const cancelPasswordHandler = () => {
  // 调整默认或缓存页面
  resetDefaultRoute(window.sessionStorage.getItem('login') || '')
}

/**
 *
 */
const submitPasswordHandler = async () => {
  const flag = actions.validForm()
  if (!flag) return
  const send = {
    oldPassword: state.send2.oldPassword,
    newPassword: state.send2.newPassword
  }
  await sendServiceData(updateUserPasswordApi, send, state)
  popMessage('密码修改成功！')
  // 更新记住登录信息
  if (state.remCatch) catchUserPwd()
  // 调整默认或缓存页面
  resetDefaultRoute()
}

</script>

<template>
  <div class="login-container">
    <img class="login-back" src="@/assets/login/loginBg3.jpg" />

    <!--登录框-->
    <div class="login-content">
      <div class="login-box">
        <div class="login-img">
          <img class="login-form-bg" src="@/assets/login/loginMain3.jpg" />
        </div>

        <div class="login-form-box">
          <div v-if="state.sysNameType" class="title-0">
            {{ state.sysNameType }}
          </div>
          <div class="title-1">
            {{ state.sysName }}
          </div>

          <!--登录-->
          <div v-if="!state.changePassword" class="form-box">
            <div class="form-item">
              <div class="input-form">
                <v-icon icon="yonghu1" class="icon-box" />
                <input v-model.trim="state.send.username"
                       placeholder="请输入用户名"
                       @blur="actions.validFormItem('username')"
                       @keydown.enter="loginHandler" />
              </div>
            </div>
            <div class="form-error">
              {{ state.error.username }}
            </div>

            <div class="form-item">
              <div class="input-form">
                <v-icon icon="mima" class="icon-box" />
                <input v-model.trim="state.send.password"
                       placeholder="请输入密码"
                       type="password"
                       @blur="actions.validFormItem('password')"
                       @keydown.enter="loginHandler" />
              </div>
            </div>
            <div class="form-error">
              {{ state.error.password }}
            </div>

            <div class="form-item">
              <div class="input-form">
                <v-icon icon="yanzhengma" class="icon-box" />
                <input v-model.trim="state.send.code"
                       placeholder="请输入验证码"
                       @blur="actions.validFormItem('code')"
                       @keydown.enter="loginHandler" />
                <div class="img-box" @click="queryCodeImg">
                  <v-loading v-if="state.imgLoading" size="small" />
                  <img :src="state.imageSource" />
                </div>
              </div>
            </div>
            <div class="form-error">
              {{ state.error.code }}
            </div>

            <div class="form-item2">
              <el-checkbox v-model="state.remCatch">
                记住用户名密码
              </el-checkbox>
            </div>

            <div class="form-bottom">
              <div class="login-button" @click="loginHandler">
                登录
              </div>
            </div>
          </div>


          <!--修改密码-->
          <div v-else class="form-box">
            <div class="form-pwd-title">
              为了您账户安全<br />
              首次登录请先修改初始密码
            </div>
            <div class="form-item">
              <div class="input-form">
                <v-icon icon="mima" class="icon-box" />
                <input v-model.trim="state.send2.newPassword"
                       placeholder="请输入新密码"
                       type="password"
                       @blur="actions.validFormItem('newPassword')" />
              </div>
            </div>
            <div class="form-error">
              {{ state.error2.newPassword }}
            </div>

            <div class="form-item">
              <div class="input-form">
                <v-icon icon="mima" class="icon-box" />
                <input v-model.trim="state.send2.reNewPassword"
                       placeholder="请重复输入新密码"
                       type="password"
                       @blur="actions.validFormItem('reNewPassword')"
                       @keydown.enter="loginHandler" />
              </div>
            </div>
            <div class="form-error">
              {{ state.error2.reNewPassword }}
            </div>

            <div class="form-bottom">
              <div class="login-button" @click="submitPasswordHandler">
                确定
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <loading v-if="state.isLoading" />
  </div>
</template>

<style lang="scss" scoped>
.form-pwd-title{
  flex:none;
  width:100%;
  font-size: .12rem;
  color:#f56c6c;
  padding-bottom: .3rem;
  box-sizing: border-box;
  text-align: center;
}

.login-container {
  @include abs-group();
  font-size: .12rem;
  color:#000;

  .login-back {
    @include abs-group() ;
    width:100%;
    height:100%;
  }

  .login-content {
    @include abs-group();
    @include hor-group(center, center);

    .login-box {
      @include hor-group();
      width: 9.6rem;
      height: 6rem;
      min-width: 7.5rem;
      min-height:4.8rem;
      background: #fff;

      .login-img {
        flex: none;
        width: 5.3rem;
        height: 100%;
        overflow: hidden;
        position:relative;

        .login-form-bg {
          width: 100%;
          height: 100%;
        }
        .login-logo{
          position:absolute;
          width:.60rem;
          left:20px;
          top:20px;
        }
      }

      .login-form-box {
        @include ver-group(center) ;
        flex: auto;
        width: 100%;
        height: 100%;
        padding-top: .88rem;
        box-sizing: border-box;

        .login-box-bg {
          @include abs-group();
        }

        .title-0 {
          flex: none;
          width: 100%;
          font-size: .24rem;
          font-weight: 400;
          line-height: .33rem;
          letter-spacing: 2px;
          text-align: center;
          font-family: PingFangSC-Regular, PingFang SC;
        }

        .title-1 {
          flex: none;
          width: 100%;
          margin-top: .15rem;
          font-size: .48rem;
          line-height: .67rem;
          letter-spacing: 2px;
          text-align: center;
          padding: 0 .2rem;
          box-sizing: border-box;
          font-family: Helvetica;
        }

        .form-box {
          @include ver-group();
          flex: none;
          width: 100%;
          //margin-top: .6rem;
          margin-top: .8rem;
          padding: 0 .82rem;
          box-sizing: border-box;

          .form-item {
            @include hor-group();
            flex: none;
            width: 100%;
            box-sizing: border-box;
            .input-form {
              @include hor-group();
              width: 100%;
              height: .32rem;
              background: #edeff4;
              border-radius: 3px;
              overflow: hidden;

              .icon-box {
                @include hor-group(center);
                flex: none;
                width: .42rem;

                .icon-input {
                  flex: none;
                  color: #535355;
                  font-size: .15rem;
                }
              }

              input {
                @include trans-input();
                flex: auto;
                width: 100%;
                height: .32rem;
                line-height: .32rem;
                padding: 0 .15rem 0 .05rem;
                box-sizing: border-box;
                color: #292929;
                text-align: left;
              }

              .img-box {
                @include hor-group(center);
                flex: none;
                width: .95rem;
                height:100%;
                overflow: hidden;
                position:relative;

                img {
                  width:.97rem;
                }
              }
            }
          }

          .form-item2{
            @include hor-group(start,start);
            flex:none;
          }

          .form-error{
            font-size: .12rem;
            color:#f56c6c;
            text-align: left;
            height:.25rem;
            padding-top: .03rem;
            box-sizing: border-box;
          }

          .form-bottom{
            @include hor-group(center) ;
            flex:none;
            width:100%;
          }
          .login-button {
            flex: none;
            width: 1.33rem;
            height: .40rem;
            background: linear-gradient(135deg, rgb(105, 141, 255) 0% , rgb(13, 76, 253) 100%);
            line-height: .40rem;
            text-align: center;
            vertical-align: middle;
            color: #fff;
            font-size: .14rem;
            cursor: pointer;
            border-radius: .2rem;
          }
          .login-button2 {
             @extend .login-button;
            width: 1rem;
          }
          .cancel-button {
            flex: none;
            width: 1rem;
            height: .40rem;
            background: linear-gradient(135deg, rgb(105, 255, 255) 0% , rgb(105, 141, 255) 100%);
            line-height: .40rem;
            text-align: center;
            vertical-align: middle;
            color: #fff;
            font-size: .14rem;
            cursor: pointer;
            border-radius: .2rem;
            margin-right: .2rem;
          }

        }

      }


    }
  }

}

</style>
